#if DEBUG_VERSION
if (!dafos) {
  throw new Error("Dafos namespace not found!");
}
#endif

#if HELPTAB

dafos.onHelpTabActivated = function() {  
  if (dafos.helptab == null) {
    dafos.helptab = new dafos.HelpTab(document.getElementById("helptab"), dafos.ui);
  }
  TRACK("tab/help");
  RESIZE();
};

/**
 * Constructor
 */
dafos.HelpTab = function(parent, ui) {
  LOG("[HelpTab]");
  this.gadgetui = ui;
  var callbacks = {
      "onlinkclicked": dafos.bind(this.onLinkClicked, this)
  };
  this.ui = new dafos.HelpTabUI(parent, callbacks);
  this.requestHelpPage("");
};

dafos.HelpTab.prototype.requestHelpPage = function(name) {
  this.gadgetui.showLoading("help");
  var index = name.indexOf("/help/");
  index = (index == -1) ? -1 : index + 6;
  var url = "@server.deploy.base@/help/" + name.substring(index);
  LOG("requesting help url", url);
  var params = {};
  params[gadgets.io.RequestParameters.CONTENT_TYPE] = 
      gadgets.io.ContentType.TEXT;
  gadgets.io.makeRequest(url, dafos.bind(this.onHelpPage, this), params);
};

dafos.HelpTab.prototype.onHelpPage = function(data) {
  LOG("[onHelpPage]", data);
  this.gadgetui.hideLoading("help"); 
  var corpus = data.text.toLowerCase();
  var startindex = corpus.indexOf('<!-- starthelpcontent -->');
  if (startindex != -1) {
    startindex += 25;
  }
  var endindex = corpus.indexOf("<!-- endhelpcontent -->");
  this.ui.renderHelpPage(data.text.substring(startindex, endindex));
};

dafos.HelpTab.prototype.onLinkClicked = function(url, e) {
  e34.$("helptab-context-message").hide();
  this.requestHelpPage(url);
  if (e.stopPropagation) {
    e.stopPropagation();
  }
  return false;
};

/**
 * Constructor
 */
dafos.HelpTabUI = function(parent, callbacks) {
  LOG("[HelpTabUI]");
  this.dom_parent_ = parent;
  this.dom_output_ = e34.$("helptab-output");
  this.callbacks_ = callbacks;
  this.render();
};

dafos.HelpTabUI.prototype.render = function() {
  e34.$("helptab").removeClass("hidden");
};

dafos.HelpTabUI.prototype.renderHelpPage = function(content) {
  this.dom_output_.removeAllChildren();
  this.dom_output_.getElement().innerHTML = content;
  RESIZE();
  
  var anchors = this.dom_output_.$T("a");
  for (var i = 0, anchor; anchor = anchors[i]; i++) {
    if (anchor.hasClass("external")) {
      anchor.getElement().target = "_blank";
    } else {
      var dest = anchor.getElement().href;
      anchor.getElement().setAttribute("href", "javascript:void(0);");
      anchor.addOnClickHandler(this.getClickHandler(this.callbacks_.onlinkclicked, dest));
    }
  }
};

dafos.HelpTabUI.prototype.getClickHandler = function(callback, destination) {
  return function(e) {
    callback(destination, e);
  }
};



#endif
